import { Base64 } from 'js-base64';
import getLyricData from '@/api/song';
import { ERR_OK } from '@/common/js/config';

export class Song {
  constructor({ id, mid, singer, name, album, duration, image, url }) {
    this.id = id;
    this.mid = mid;
    this.singer = singer;
    this.name = name;
    this.album = album;
    this.duration = duration;
    this.image = image;
    this.url = url;
  }
  getLyric() {
    if (this.lyric) {
      // 循环播放不用再请求
      return Promise.resolve(this.lyric);
    }
    return new Promise((resolve, reject) => {
      getLyricData(this.mid).then((res) => {
        if (res.retcode === ERR_OK) {
          this.lyric = Base64.decode(res.lyric);
          resolve(this.lyric);
        } else {
          reject('no lyric');
        }
      });
    });
  }
}
function filterSinger(singer) {
  const ret = [];
  singer.forEach((item) => {
    ret.push(item.name);
  });
  return ret.join('/');
}
export function findSong(list, song) {
  return list.findIndex(item => item.id === song.id);
}
export function createSong(musicData) {
  const song = new Song({
    id: musicData.songid,
    mid: musicData.songmid,
    singer: filterSinger(musicData.singer),
    name: musicData.songname,
    album: musicData.albumname,
    duration: musicData.interval,
    image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
    url: `http://ws.stream.qqmusic.qq.com/${musicData.songid}.m4a?fromtag=46`,
  });
  return song;
}
